<script setup lang="ts">
import { ref, getCurrentInstance } from "vue";
import energyBord from "../../components/energyBord.vue";
import echartsChart from "@/views/common/components/echartsChart/index.vue";
import barCharts from "@/views/common/energy/components/barCharts/index.vue";
import scrollTableCard from "@/views/common/energy/components/scrollTableCard.vue";
import yearPicker from "../../components/yearPicker.vue";
import { pieChartAll, scrollTableAll, energyDeskAll, barLineAll } from "@/api/modules/energy";
import { PxMessage } from "px-ui";

const { proxy }: any = getCurrentInstance();

interface queryForm {
  queryTimeGranularity?: string;
  startTime?: string;
  endTime?: string;
  level?: string;
}

type itemStyleType = {
  [key: string]: string;
};

interface dataType {
  name: string;
  value: number;
  itemStyle?: itemStyleType;
}

const classNameArr = ref([
  {
    name: "厂1",
    value: "1"
  },
  {
    label: "厂2",
    value: "2"
  }
]);
const dataList = ref([
  {
    name: "能耗费用",
    valueFormat: "123,45",
    unit: "万元",
    percent: "12",
    icon: "elec_money"
  },
  {
    name: "累计用电量",
    valueFormat: "112,35",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_used"
  },
  {
    name: "累计折标煤",
    valueFormat: "221,42",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_mei"
  },
  {
    name: "累计用电量",
    valueFormat: "112,35",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_used"
  },
  {
    name: "累计折标煤",
    valueFormat: "221,42",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_mei"
  },
  {
    name: "累计用电量",
    valueFormat: "112,35",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_used"
  },
  {
    name: "累计折标煤",
    valueFormat: "221,42",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_mei"
  },
  {
    name: "累计碳排放",
    valueFormat: "123,12",
    unit: "tCO2e",
    percent: "12",
    icon: "elec_co2"
  }
]);

const queryParams = ref<queryForm>({
  queryTimeGranularity: "DAY",
  level: ""
});
const queryTimeType = ref("DAY");
const tabPosition = ref("overView");

const queryRef = ref();

const handleChangeFn = (val: string) => {
  console.log(val);
  dateRange.value = [];
};

const dateRange = ref<Array<string>>([]);
const barOptions = ref<CommonEcharts.CommonEchartsOption>(null);

const labelLayoutFn = (ec: any, data: Array<dataType>, title: string) => {
  const { getWidth = null } = ec;
  const labelLayout = function (params) {
    if (!getWidth) return null;
    const isLeft = params.labelRect.x < getWidth() / 2;
    const points = params.labelLinePoints;
    points[2][0] = isLeft ? params.labelRect.x : params.labelRect.x + params.labelRect.width;
    return { labelLinePoints: points };
  };
  const options: CommonEcharts.CommonEchartsOption = {
    // title: {
    //   text: `今日机台\n${title}`,
    //   textStyle: {
    //     color: "#555",
    //     fontSize: 16,
    //     fontWeight: 500,
    //     lineHeight: 18
    //   },
    //   left: "center",
    //   top: "center"
    // },
    tooltip: {
      trigger: "item",
      formatter: "{a} <br/>{b} : {c}台 ({d}%)"
    },
    grid: {
      left: 0,
      right: 0,
      top: 0,
      bottom: 0,
      containLabel: true
    },
    series: [
      {
        name: title,
        type: "pie",
        radius: [42, 68],
        center: ["50%", "50%"],
        label: {
          alignTo: "edge",
          formatter: "{name|{b}}\n{num|{c}台}{percent| ( {d}% )}",
          minMargin: 2,
          edgeDistance: 10,
          lineHeight: 20,
          rich: {
            num: {
              fontSize: 14,
              color: "#222",
              lineHeight: 20,
              fontWeight: 600
            },
            percent: {
              fontSize: 10,
              color: "#333",
              lineHeight: 20
            }
          }
        },
        labelLine: {
          length: 15,
          length2: 0,
          maxSurfaceAngle: 80
        },
        labelLayout,
        data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: "rgba(0, 0, 0, 0.5)"
          }
        }
      }
    ]
  };
  return options;
};

const labelLayoutStatusFn = async (ec: any) => {
  const title = "";
  // const params = getParams();
  // const res = await getFabStatus(params);
  // if (!res?.length) return null;
  // const data = res.map(item => {
  // const { deviceStatus: name, num: value } = item;
  // const s = status.find(item => item.value === name.toLowerCase());
  // const itemStyle = s ? { color: s.backgroundColor } : null;
  // return { name, value, itemStyle };
  // });
  const data = [
    {
      name: "运行",
      value: 12,
      itemStyle: {
        color: "#0099FF"
      }
    },
    {
      name: "关机",
      value: 12,
      itemStyle: {
        color: "#FF9900"
      }
    },
    {
      name: "故障",
      value: 12,
      itemStyle: {
        color: "#FF0000"
      }
    }
  ];
  return labelLayoutFn(ec, data, title);
};

const labelLayoutPercentFn = async (ec: any) => {
  const title = "";
  // const params = getParams();
  // const res = await getFabStatus(params);
  // if (!res?.length) return null;
  // const data = res.map(item => {
  // const { deviceStatus: name, num: value } = item;
  // const s = status.find(item => item.value === name.toLowerCase());
  // const itemStyle = s ? { color: s.backgroundColor } : null;
  // return { name, value, itemStyle };
  // });
  const data = [
    {
      name: "运行",
      value: 12,
      itemStyle: {
        color: "#0099FF"
      }
    },
    {
      name: "关机",
      value: 12,
      itemStyle: {
        color: "#FF9900"
      }
    },
    {
      name: "故障",
      value: 12,
      itemStyle: {
        color: "#FF0000"
      }
    }
  ];
  return labelLayoutFn(ec, data, title);
};

// 获取对象数组某一项value组成的数组
const getValueList = (arr: any[], key: number | string) => {
  let valueList = [];
  arr.forEach(item => {
    valueList.push(item[key]);
  });
  return valueList;
};

// 柱状图
const labelLayoutRightFn = async (ec: any) => {
  const title = "能耗趋势";
  const unit = "KWH";
  const params = getParams();
  // const isWater = ec.energyType === "HOT_WATER";
  // const res: any = await barChart(isWater, params);
  const res: any = {};
  // if (!res?.detail || !res?.detail.length) return null;
  // const xData = getValueList(res?.detail, "timeFormat") || ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"];
  const xData = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"];
  // const seriesData1 = getValueList(res?.detail, "value") || [12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122];
  // const seriesData2 = [2, 23, 11, 22, 33, 44, 55, 66, 77, 88, 99, 100];
  // const seriesData3 = [2.0, 2.3, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.0];
  const seriesData1 = [12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122];
  const seriesData2 = [2, 23, 11, 22, 33, 44, 55, 66, 77, 88, 99, 100];
  const seriesData3 = [2.0, 2.3, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.0];
  barOptions.value = labelLayoutFnBar(ec, xData, seriesData1, seriesData2, seriesData3, title, unit);
};

// 柱状图
const labelLayoutFnBar = (ec: any, xdata: string[], data1: number[], data2: number[], data3: number[], title: string, unit: string) => {
  const options: CommonEcharts.CommonEchartsOption = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999"
        }
      }
    },
    grid: {
      left: "1%",
      right: "1%",
      bottom: 0,
      containLabel: true
    },
    legend: {
      data: ["能耗值", "同比能耗值", "同比百分比"]
    },
    // calculable: true,
    xAxis: [
      {
        type: "category",
        // prettier-ignore
        data: xdata
      }
    ],
    yAxis: [
      {
        type: "value",
        name: `单位：${unit}`,
        nameTextStyle: {
          color: "#aaa"
        }
      }
    ],
    series: [
      {
        name: "能耗值",
        type: "bar",
        data: data1,
        itemStyle: {
          color: "#3B82F6"
        },
        // markPoint: {
        //   data: [
        //     { type: "max", name: "Max" },
        //     { type: "min", name: "Min" }
        //   ],
        //   // 修改标记点的样式
        //   itemStyle: {
        //     color: "#FFBC68" // 标记点的颜色
        //   },
        //   label: {
        //     show: true, // 显示标签
        //     formatter: `{c}${unit}`, // 标签格式
        //     color: "black" // 标签颜色
        //   }
        // },
        markLine: {
          data: [{ type: "average", name: "Avg" }],
          label: {
            show: true, // 显示标签
            position: "middle", // 标签位置
            formatter: `平均值：{c}${unit}`, // 标签格式
            color: "#3B82F6" // 标签颜色
          }
        }
      },
      {
        name: "同比能耗值",
        type: "bar",
        data: data2,
        itemStyle: {
          color: "#28D892"
        }
        // markPoint: {
        //   data: [
        //     { type: "max", name: "Max" },
        //     { type: "min", name: "Min" }
        //   ],
        //   // 修改标记点的样式
        //   itemStyle: {
        //     color: "#FFBC68" // 标记点的颜色
        //   },
        //   label: {
        //     show: true, // 显示标签
        //     formatter: `{c}${unit}`, // 标签格式
        //     color: "black" // 标签颜色
        //   }
        // }
        // markLine: {
        //   data: [{ type: "average", name: "Avg" }],
        //   label: {
        //     show: true, // 显示标签
        //     position: "middle", // 标签位置
        //     formatter: `平均值：{c}${unit}`, // 标签格式
        //     color: "#3B82F6" // 标签颜色
        //   }
        // }
      },
      {
        name: "同比百分比",
        type: "line",
        data: data3,
        itemStyle: {
          color: "#FDA620"
        }
      }
    ]
  };
  return options;
};

const getParams = () => {
  return {};
};

/** 搜索按钮操作 */
function handleQuery() {
  proxy.$refs["queryRef"].validate(valid => {
    if (!valid) return;
    if (queryParams.value.queryTimeGranularity) {
      if (!checkDate()) {
        return PxMessage({
          type: "warning",
          message: "时间范围不能为空"
        });
      }
    } else {
    }
  });
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  dateRange.value = [];
  queryParams.value.queryTimeGranularity = "";
  queryParams.value.startTime = "";
  queryParams.value.endTime = "";
  queryTimeType.value = "DAY";
  handleQuery();
}

// 可选择区间，initYear传参，不传则所有年份有效，小于0判断一下？
const dateValue = ref<any>({});
// 选完/输入完成的回调
const updateStatisticYear: any = (startYear: number, endYear: number) => {
  console.log("选中年份", startYear, endYear);
  dateRange.value = [startYear ? startYear.toString() : "", endYear ? endYear.toString() : ""];
};

// 校验时间范围不为空
const checkDate = () => {
  if (queryParams.value.queryTimeGranularity) {
    if (dateRange.value && dateRange.value.length) {
      return true;
    }
    if (queryParams.value.startTime && queryParams.value.endTime) {
      return true;
    }
  }
};
</script>

<template>
  <div>
    <div class="top_query">
      <px-radio-group v-model="tabPosition" class="tabSwitch">
        <px-radio-button label="supplyConsume">供给与消耗</px-radio-button>
        <px-radio-button label="overView">总览</px-radio-button>
        <px-radio-button label="area">区域</px-radio-button>
        <px-radio-button label="fab">机台</px-radio-button>
      </px-radio-group>
      <px-form ref="queryRef" class="custom-form-ui inspection-form" :model="queryParams" :inline="true" label-width="100px">
        <px-form-item label="统计维度" prop="dataFormat" style="width: 330px">
          <px-radio-group v-model="queryParams.queryTimeGranularity" style="margin-left: 10px" @change="handleChangeFn">
            <px-radio size="small" label="HONR">小时</px-radio>
            <px-radio size="small" label="DAY">日</px-radio>
            <px-radio size="small" label="MONTH">月</px-radio>
            <px-radio size="small" label="YEAR">年</px-radio>
          </px-radio-group>
        </px-form-item>
        <px-form-item label="时间范围" style="width: 380px">
          <px-time-picker
            v-if="queryParams.queryTimeGranularity === 'HONR'"
            v-model="dateRange"
            is-range
            range-separator="-"
            format="HH"
            value-format="HH"
            start-placeholder="开始小时"
            end-placeholder="结束小时"
          />
          <px-date-picker
            v-if="queryParams.queryTimeGranularity === 'DAY'"
            v-model="dateRange"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
          <px-date-picker
            v-if="queryParams.queryTimeGranularity === 'MONTH'"
            v-model="dateRange"
            type="monthrange"
            format="YYYY-MM"
            value-format="YYYY-MM"
            range-separator="-"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
          />
          <!-- <div v-else-if="queryParams.queryTimeGranularity === 'YEAR'" class="select_year">
            <px-date-picker v-model="queryParams.startTime" value-format="YYYY" type="year" placeholder="开始年份" />
            <span>&nbsp;-&nbsp;</span>
            <px-date-picker v-model="queryParams.endTime" value-format="YYYY" type="year" placeholder="结束年份" />
          </div> -->
          <div v-if="queryParams.queryTimeGranularity === 'YEAR'">
            <yearPicker ref="statisticPicker" :labelWidth="0" labelText="" :initYear="dateValue" @updateTimeRange="updateStatisticYear" />
          </div>
        </px-form-item>
        <px-form-item label="厂区">
          <px-select v-model="queryParams.level" clearable placeholder="请选择层级">
            <px-option v-for="item in classNameArr" :key="item.value" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-button type="primary" icon="" @click="handleQuery">搜索</px-button>
        <px-button icon="" @click="resetQuery">重置</px-button>
      </px-form>
    </div>
    <div v-if="tabPosition === 'overView'" class="overView">
      <div class="top_con">
        <div class="top_con_item">
          <energyBord title="总览" :width="500" :height="303" :data-list="dataList" />
        </div>
        <div class="top_con_item">
          <barCharts
            ref="energyConsumeRef"
            title="能耗趋势"
            showDownload
            :boxShadow="true"
            :width="716"
            :height="303"
            :options="barOptions"
            @topRight="labelLayoutRightFn(null)"
          />
        </div>
      </div>
      <div class="mid_con">
        <div class="mid_con_item">
          <echartsChart title="厂务、机台能耗占比" showDownload :width="320" :height="267" :boxShadow="true" :labelLayoutFn="labelLayoutStatusFn" />
        </div>
        <div class="mid_con_item">
          <scrollTableCard title="系统能耗排行" :width="440" :height="267" :data-list="dataList" showDownload />
        </div>
        <div class="mid_con_item">
          <echartsChart title="系统耗电占比" showDownload :width="500" :height="267" :boxShadow="true" :labelLayoutFn="labelLayoutPercentFn" />
        </div>
      </div>
      <div class="btn_con">
        <div class="btn_con_item">
          <echartsChart title="子系统耗电" showDownload :width="685" :height="306" :boxShadow="true" :labelLayoutFn="labelLayoutStatusFn" />
        </div>
      </div>
    </div>
    <div v-else class="area">
      <div class="top_con">
        <div class="top_con_item">
          <barCharts
            title="能耗趋势"
            showDownload
            :boxShadow="true"
            :width="716"
            :height="303"
            :options="barOptions"
            @topRight="labelLayoutRightFn(null)"
          />
        </div>
      </div>
      <div class="mid_con">
        <div class="mid_con_item">
          <echartsChart title="厂务、机台能耗占比" showDownload :width="320" :height="267" :boxShadow="true" :labelLayoutFn="labelLayoutStatusFn" />
        </div>
        <div class="mid_con_item">
          <scrollTableCard title="系统能耗排行" :width="440" :height="267" :data-list="dataList" showDownload />
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.top_query {
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: left;
  width: 100%;
  min-width: 1300px;
  height: auto;
  padding: 16px 24px;
  margin-bottom: 16px;
  line-height: 44px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 10px 0 rgb(0 37 86 / 12%);

  /*
  * tab样式
  */
  .tabSwitch {
    min-width: 286px;
    padding: 0 5px;
    margin-right: 20px;
    background-color: #f4f4f4;
    border-radius: 4px;

    :deep(.px-radio-button__inner) {
      background-color: #f4f4f4;
      border: none;
    }

    :deep(.is-active) {
      border: none;

      .px-radio-button__inner {
        background-color: var(--px-color-primary);
        border-radius: 4px;
      }
    }
  }

  .select_year {
    display: flex;
    flex-wrap: nowrap;
    align-items: center;
    justify-content: left;
  }

  .px-form-item {
    margin-bottom: 0;
  }
}

.overView {
  .top_con {
    display: flex;
    justify-content: space-between;
    width: 100%;
    min-width: 1300px;
    height: 303px;
    margin-bottom: 16px;

    .top_con_item:nth-child(1) {
      width: 42%;
      margin-right: 16px;
    }

    .top_con_item:nth-child(2) {
      width: 58%;
    }
  }

  .mid_con {
    display: flex;
    justify-content: space-between;
    width: 100%;
    min-width: 1300px;
    height: 267px;
    margin-bottom: 16px;

    .mid_con_item:nth-child(1) {
      width: 25%;
      margin-right: 16px;
    }

    .mid_con_item:nth-child(2) {
      width: 34%;
      margin-right: 16px;
    }

    .mid_con_item:nth-child(3) {
      width: 41%;
    }
  }

  .btn_con {
    width: 100%;
    min-width: 1300px;
    height: 306px;

    .btn_con_item {
      width: 100%;
      height: 100%;
    }
  }
}

.area {
  .top_con {
    display: flex;
    justify-content: center;
    width: 100%;
    min-width: 1300px;
    height: 303px;
    margin-bottom: 16px;

    .top_con_item {
      width: 100%;
      height: 100%;
    }
  }

  .mid_con {
    display: flex;
    justify-content: space-between;
    width: 100%;
    min-width: 1300px;
    height: 267px;
    margin-bottom: 16px;

    .mid_con_item {
      width: 50%;
    }

    .mid_con_item:nth-child(1) {
      margin-right: 16px;
    }
  }
}
</style>
